/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pigx.shop.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.constant.enums.BooleanTypeEnum;
import com.pig4cloud.pigx.common.core.constant.enums.CouponUseStatusEnum;
import com.pig4cloud.pigx.common.core.constant.enums.DeleteFlagEnum;
import com.pig4cloud.pigx.common.core.constant.enums.UserTypeEnum;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.shop.api.dto.GoodsMaterialDTO;
import com.pig4cloud.pigx.shop.api.entity.GoodsServer;
import com.pig4cloud.pigx.shop.api.feign.RemoteGoodsMaterialService;
import com.pig4cloud.pigx.shop.api.feign.RemoteGoodsServerService;
import com.pig4cloud.pigx.shop.user.api.entity.*;
import com.pig4cloud.pigx.shop.user.api.vo.ShopEquityCouponVO;
import com.pig4cloud.pigx.shop.user.api.vo.ShopEquityVO;
import com.pig4cloud.pigx.shop.user.api.vo.ShopUserVO;
import com.pig4cloud.pigx.shop.user.mapper.PromotionChannelMapper;
import com.pig4cloud.pigx.shop.user.mapper.ShopEquityMapper;
import com.pig4cloud.pigx.shop.user.service.ShopCouponService;
import com.pig4cloud.pigx.shop.user.service.ShopEquityCouponService;
import com.pig4cloud.pigx.shop.user.service.ShopEquityService;
import com.pig4cloud.pigx.shop.user.service.ShopUserCouponService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 权益包
 *
 * @author pigx code generator
 * @date 2024-01-14 17:54:24
 */
@Slf4j
@Service
@AllArgsConstructor
public class ShopEquityServiceImpl extends ServiceImpl<ShopEquityMapper, ShopEquity> implements ShopEquityService {

	private final ShopEquityCouponService shopEquityCouponService;

	private final RemoteGoodsMaterialService remoteGoodsMaterialService;

	private final PromotionChannelMapper promotionChannelMapper;

	private final ShopUserCouponService shopUserCouponService;

	private final RemoteGoodsServerService remoteGoodsServerService;

	/**
	 * 分页查询
	 * @param page
	 * @param shopEquity
	 * @return
	 */
	@Override
	public IPage<ShopEquityVO> getPage(Page page, ShopEquity shopEquity) {
		IPage<ShopEquityVO> result = new Page<>();
		LambdaQueryWrapper<ShopEquity> lqwShopEquity = new LambdaQueryWrapper<>();
		if (!StringUtils.isEmpty(shopEquity.getEquityName())) {
			lqwShopEquity.like(ShopEquity::getEquityName, shopEquity.getEquityName());
		}
		if (!StringUtils.isEmpty(shopEquity.getStatus())) {
			lqwShopEquity.eq(ShopEquity::getStatus, shopEquity.getStatus());
		}
		IPage<ShopEquity> items = this.page(page, lqwShopEquity);
		if (items.getRecords().size() > 0) {
			List<String> channelCodes = new ArrayList<>();
			result = items.convert(u -> {
				ShopEquityVO v = new ShopEquityVO();
				BeanUtils.copyProperties(u, v);
				channelCodes.add(u.getChannelCode());
				return v;
			});
			// 去重
			List<String> distinctList = channelCodes.stream().distinct().collect(Collectors.toList());
			// 查询渠道名称
			LambdaQueryWrapper<PromotionChannel> lqwPromotionChannel = new LambdaQueryWrapper<>();
			lqwPromotionChannel.in(PromotionChannel::getChannelCode, distinctList);
			lqwPromotionChannel.eq(PromotionChannel::getDelFlag, DeleteFlagEnum.VALID.getType());
			List<PromotionChannel> promotionChannels = promotionChannelMapper.selectList(lqwPromotionChannel);
			result.getRecords().forEach(item -> {
				Optional<PromotionChannel> promotionChannel = promotionChannels.stream()
						.filter(p -> p.getChannelCode().equals(item.getChannelCode())).findFirst();
				if (promotionChannel.isPresent()) {
					item.setPromotionChannelName(promotionChannel.get().getChannelName());
				}
			});
		}
		return result;
	}

	/**
	 * 添加
	 * @param shopEquityVO
	 * @return
	 */
	@Override
	public R addEquity(ShopEquityVO shopEquityVO) {
		this.save(shopEquityVO);
		Long equityId = shopEquityVO.getId();
		if (shopEquityVO.getEquityCoupons().size() > 0) {
			shopEquityVO.getEquityCoupons().forEach(coupon -> {
				coupon.setEquityId(equityId);
			});
			shopEquityCouponService.saveBatch(shopEquityVO.getEquityCoupons());
		}
		return R.ok();
	}

	/**
	 * 修改
	 * @param shopEquityVO
	 * @return
	 */
	@Override
	public R updateEquity(ShopEquityVO shopEquityVO) {
		this.updateById(shopEquityVO);
		Long equityId = shopEquityVO.getId();
		// 先删除
		LambdaQueryWrapper<ShopEquityCoupon> lqwShopEquityCoupon = new LambdaQueryWrapper<>();
		lqwShopEquityCoupon.eq(ShopEquityCoupon::getEquityId, equityId);
		shopEquityCouponService.remove(lqwShopEquityCoupon);

		if (shopEquityVO.getEquityCoupons().size() > 0) {
			// 后添加
			shopEquityVO.getEquityCoupons().forEach(coupon -> {
				coupon.setEquityId(equityId);
			});
			shopEquityCouponService.saveBatch(shopEquityVO.getEquityCoupons());
		}

		return R.ok();
	}

	/**
	 * 获取详情
	 * @param id
	 * @return
	 */
	@Override
	public R getEquityInfo(Long id) {
		ShopEquityVO result = new ShopEquityVO();
		ShopEquity shopEquity = this.getById(id);
		BeanUtils.copyProperties(shopEquity, result);

		// 获取服务列表
		String[] serviceIds = result.getGoodsServerIds().split(",");
		if (serviceIds.length > 0) {
			List<Long> ids = new ArrayList<>();
			for (String serviceId : serviceIds) {
				ids.add(Long.parseLong(serviceId));
			}
			R<List<GoodsServer>> GoodsServerR = remoteGoodsServerService.getListByIds(ids, SecurityConstants.FROM_IN);
			List<GoodsServer> GoodsServers = GoodsServerR.getData();
			result.setServers(GoodsServers);
		}

		// 获取图片
		getShopEquityImages(result);
		// 获取优惠券
		List<ShopEquityCoupon> coupons = shopEquityCouponService
				.list(Wrappers.<ShopEquityCoupon>lambdaQuery().eq(ShopEquityCoupon::getEquityId, id));
		result.setEquityCoupons(coupons);
		return R.ok(result);
	}

	/**
	 * 删除权益包
	 * @param id
	 * @return
	 */
	@Override
	public R removeEquity(Long id) {
		this.removeById(id);
		// 删除绑定的优惠券
		LambdaQueryWrapper<ShopEquityCoupon> lqwShopEquityCoupon = new LambdaQueryWrapper<>();
		lqwShopEquityCoupon.eq(ShopEquityCoupon::getEquityId, id);
		shopEquityCouponService.remove(lqwShopEquityCoupon);
		return R.ok();
	}

	/**
	 * 获取权益包列表
	 * @param shopEquity
	 * @return
	 */
	@Override
	public List<ShopEquityVO> getShopEquityList(ShopEquity shopEquity) {
		List<ShopEquityVO> result = new ArrayList<>();
		LambdaQueryWrapper<ShopEquity> lqwShopEquity = new LambdaQueryWrapper<>();
		lqwShopEquity.eq(ShopEquity::getStatus, BooleanTypeEnum.TRUE.getType());
		List<ShopEquity> list = this.list(lqwShopEquity);
		if (list.size() > 0) {
			list.forEach(item -> {
				ShopEquityVO vo = new ShopEquityVO();
				BeanUtils.copyProperties(item, vo);
				// 获取图片
				getShopEquityImages(vo);
				result.add(vo);
			});
		}
		return result;
	}

	/**
	 * 获取权益包
	 * @param shopEquityVO
	 * @return
	 */
	@Override
	public R receiveShopEquity(ShopEquityVO shopEquityVO) {
		Long equityId = shopEquityVO.getId();
		Long shopUserId = shopEquityVO.getShopUserId();
		Long equityOrderId = shopEquityVO.getEquityOrderId();
		log.info("用户Id:" + shopUserId + "权益包Id:" + equityId);
		ShopEquity shopEquity = this.getById(equityId);
		if (shopEquity == null) {
			log.info("用户Id:" + shopUserId + "当前权益包已被删除:" + equityId);
			return R.failed("当前权益包已被删除");
		}

		// 获取优惠券
		List<ShopEquityCoupon> coupons = shopEquityCouponService
				.list(Wrappers.<ShopEquityCoupon>lambdaQuery().eq(ShopEquityCoupon::getEquityId, shopEquity.getId()));
		if (coupons.size() > 0) {
			log.info("开始发放优惠券,用户Id:" + shopUserId + "权益包Id:" + equityId);
			List<ShopUserCoupon> shopUserCoupons = new ArrayList<>();
			coupons.forEach(coupon -> {
				// 发放优惠券
				ShopUserCoupon shopUserCoupon = new ShopUserCoupon();
				shopUserCoupon.setShopUserId(shopUserId);
				shopUserCoupon.setCouponId(coupon.getCouponId());
				shopUserCoupon.setUseStatus(CouponUseStatusEnum.NOT_USED.getType());
				shopUserCoupon.setEquityId(equityId);
				shopUserCoupon.setEquityOrderId(equityOrderId);
				shopUserCoupons.add(shopUserCoupon);
				log.info("开始发放优惠券,用户Id:" + shopUserId + "权益包Id:" + equityId + "优惠券ID:" + coupon.getCouponId());
			});
			shopUserCouponService.saveBatch(shopUserCoupons);
			log.info("结束发放优惠券,用户Id:" + shopUserId + "权益包Id:" + equityId);
		}
		return R.ok();
	}

	/**
	 * 获取图片
	 * @param vo
	 */
	private void getShopEquityImages(ShopEquityVO vo) {
		GoodsMaterialDTO goodsMaterialDTO = new GoodsMaterialDTO();
		goodsMaterialDTO.setImageIds(vo.getBannerImages());
		// 轮播图
		R<String> bannerImages = remoteGoodsMaterialService.convertImageIdToUrl(goodsMaterialDTO,
				SecurityConstants.FROM_IN);
		vo.setBannerImages(bannerImages.getData());

		goodsMaterialDTO.setImageIds(vo.getDetailImages());
		// 详情图
		R<String> detailImages = remoteGoodsMaterialService.convertImageIdToUrl(goodsMaterialDTO,
				SecurityConstants.FROM_IN);
		vo.setDetailImages(detailImages.getData());
	}

}
